package org.easyx.ui.controller.sys;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.easyx.core.ui.easyui.PageBean;
import org.easyx.core.ui.easyui.PageParam;
import org.easyx.core.utils.ObjKit;
import org.easyx.ser.sys.entity.SysUser;
import org.easyx.ser.sys.entity.SysUserRole;
import org.easyx.ser.sys.serivce.SysUserRoleService;
import org.easyx.ser.sys.serivce.SysUserService;
import org.easyx.ui.base.BaseController;
import org.easyx.ui.base.SessionUser;
import org.easyx.ui.shiro.PasswordHash;
import org.easyx.ui.util.SessionKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-09-11
 */
@Controller
@RequestMapping("/sys/sysUser")
public class SysUserController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(SysUserController.class);
	private static final String basePagePath = "sys/user/";
	
	@Autowired
    private PasswordHash passwordHash;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	/**
	 * 进入角色资源授权页面
	 */
	@RequiresPermissions("sys/sysUser/grantRole")
	@RequestMapping("/grantRolePage")
	public String grantRolePage(Long id){
		this.request.setAttribute("id", id);
		return basePagePath+"roleGrant";
	}
	
	/**
	 * 提交用户授权信息
	 */
	@RequiresPermissions("sys/sysUser/grantRole")
	@RequestMapping("/grantRole")
	public @ResponseBody Object grantRole(Long id,String roleIds){
		try {
			SysUser entity = sysUserService.selectById(id);
			if (ObjKit.isEmpty(entity)) {
				return operateError("用户ID【"+id+"】对应的用户信息不存在!");
			}
			sysUserRoleService.updateUserRole(id,roleIds);

			return operateSuccess("授权成功!");
		} catch (Exception e) {
			log.error("用户授权失败:", e);
			return operateError("授权失败!");
		}
	}
	
	@RequestMapping("/findRoleIdListByUserId")
	public @ResponseBody Object findRoleIdListByUserId(Long id){
		List<SysUserRole> list = sysUserRoleService.selectList(new EntityWrapper<SysUserRole>()
											.eq("userId",id).orderBy("id", true));
		List<Long> l = new ArrayList<Long>();
		for(SysUserRole r:list){
			l.add(r.getRoleId());
		}
		
		return operateSuccess("数据获取成功", l);
	}
	
	
	/**
	 * 进入列表页面
	 */
	@RequiresPermissions("sys/sysUser/manager")
	@RequestMapping("/manager")
	public String manager(Model model){
		SessionUser su = SessionKit.getSessionUser(request);
		model.addAttribute("sessionUser", su);
		
		return basePagePath+"list";
	}
	
	/**
	 * 查询列表数据(分页)
	 */
	@RequiresPermissions("sys/sysUser/manager")
	@RequestMapping("/dataGrid")
	public @ResponseBody Object dataGrid(PageParam pageParam, SysUser entity){
		PageBean<SysUser> pageBean = this.selectListPage(pageParam, entity, sysUserService);
		return pageBean;
	}

	@RequiresPermissions("sys/sysUser/add")
	@RequestMapping("/addPage")
	public String addPage(){
		
		return basePagePath+"add";
	}
	
	@RequiresPermissions("sys/sysUser/add")
	@RequestMapping("/add")
	public @ResponseBody Object add(@Valid SysUser entity, BindingResult result, String roleIds){
		try {
			if(result.hasErrors()){
				return operateError(result.getAllErrors().get(0).getDefaultMessage());
			}
			
			/** 数据唯一性校验 */
			List<SysUser> listByLoginName = sysUserService.selectList(
						new EntityWrapper<SysUser>().eq("loginName",entity.getLoginName()));
			if(ObjKit.isNotEmpty(listByLoginName)){
				return operateError("账号【"+entity.getLoginName()+"】已经存在，请重新填写");
			}
			List<SysUser> listByRealName = sysUserService.selectList(
					new EntityWrapper<SysUser>().eq("realName",entity.getRealName()));
			if(ObjKit.isNotEmpty(listByRealName)){
				return operateError("账号【"+entity.getRealName()+"】已经存在，请重新填写");
			}

			//生成加密参数并加密密码
			String salt = ObjKit.getUUId();
			String pwd = passwordHash.toHex(entity.getLoginPwd(), salt);
			entity.setLoginPwd(pwd);
			entity.setSalt(salt);
			
			
			entity.setCreateBy(SessionKit.getSessionUser(request).getUserId());
			if(ObjKit.isNotEmpty(roleIds)){
				sysUserService.insertWithCascade(entity,roleIds);
			}else{
				
				addOptions(entity);
				//插入数据库
				sysUserService.insert(entity);
			}
			
			return operateSuccess("数据添加成功");
		} catch (Exception e) {
			log.error("添加数据出现异常:", e);
			return operateError("保存数据失败");
		}
	}
	
	@RequiresPermissions("sys/sysUser/edit")
	@RequestMapping("/editPage")
	public String editPage(Model model, Long id){
		try {
			SysUser entity = sysUserService.selectById(id);
			if (ObjKit.isEmpty(entity)) {
				log.error("获取到的数据为空！id="+id);
			}
			model.addAttribute("entity",entity);
			
			//roleIds
			StringBuffer buffer = new StringBuffer("");
			List<SysUserRole> urList = sysUserRoleService.selectList(new EntityWrapper<SysUserRole>().eq("userId",id));
			if(urList!=null){
				for(SysUserRole ur:urList){
					buffer.append(ur.getRoleId()).append(",");
				}
			}
			model.addAttribute("roleIds", buffer.toString());
			
		} catch (Exception e) {
			log.error("进入编辑页面时，获取数据出现异常:id="+id, e);
		}
		
		return  basePagePath+"edit" ;
	}
	
	@RequiresPermissions("sys/sysUser/edit")
	@RequestMapping("/edit")
	public @ResponseBody Object edit(@Valid SysUser entity, BindingResult result, String roleIds){
		try {
			if(result.hasErrors()){
				return operateError(result.getAllErrors().get(0).getDefaultMessage());
			}
			
			Long id = entity.getId();
			SysUser oldObj = sysUserService.selectById(id);
			if (ObjKit.isEmpty(oldObj)) {
				return operateError("无法获取要修改的数据");
			}
			/** 数据唯一性校验逻辑*/
			if(!oldObj.getLoginName().equals(entity.getLoginName())){
				List<SysUser> listByLoginName = sysUserService.selectList(
						new EntityWrapper<SysUser>().eq("loginName",entity.getLoginName()));
				if(ObjKit.isNotEmpty(listByLoginName)){
					return operateError("账号【"+entity.getLoginName()+"】已经存在，请重新填写");
				}
			}
			if(!oldObj.getRealName().equals(entity.getRealName())){
				List<SysUser> listByRealName = sysUserService.selectList(
						new EntityWrapper<SysUser>().eq("realName",entity.getRealName()));
				if(ObjKit.isNotEmpty(listByRealName)){
					return operateError("账号【"+entity.getRealName()+"】已经存在，请重新填写");
				}
			}
			
			StringBuffer buffer = new StringBuffer("");
			List<SysUserRole> urList = sysUserRoleService.selectList(new EntityWrapper<SysUserRole>().eq("userId",id));
			if(urList!=null){
				for(SysUserRole ur:urList){
					buffer.append(ur.getRoleId()).append(",");
				}
			}
			String oldRoleIds = buffer.toString();
			if(!oldRoleIds.equals(roleIds)){
				sysUserService.updateWithCascade(entity,roleIds);
			}else{
				//更新数据库
				sysUserService.updateById(entity);
			}
			
			return operateSuccess("数据修改成功");
		} catch (Exception e) {
			log.error("保存修改数据出现异常:", e);
			return operateError("数据修改失败");
		}
	}
	
	@RequiresPermissions("sys/sysUser/delete")
	@RequestMapping("/delete")
	public @ResponseBody Object delete(Long id){
		try {
			SessionUser su = SessionKit.getSessionUser(request);
			if(su.getUserId().compareTo(id)==0){
				return operateError("自己不可删除自己哦");
			}
			
			SysUser entity = sysUserService.selectById(id);
			if (ObjKit.isEmpty(entity)) {
				return operateError("无法获取要删除的数据");
			}
			
			sysUserService.deleteWithCascade(entity);
			
			return operateSuccess("数据删除成功");
		} catch (Exception e) {
			log.error("删除出现异常:id="+id, e);
			return operateError("数据删除失败");
		}
	}
	
	@RequestMapping("/editCurrentUserPwdPage")
	public String editCurrentUserPwdPage(Model model){
		try {
			
			Long userid = SessionKit.getSessionUser(request).getUserId();
			SysUser u = sysUserService.selectById(userid);
			
			model.addAttribute("entity",u);
			
		} catch (Exception e) {
			log.error("进入修改当前用户密码页面出现异常：", e);
		}
		
		return  basePagePath+"editPwd" ;
	}
	
	@RequestMapping("/editUserPwd")
	public @ResponseBody Object editUserPwd(String oldPwd,String pwd,String rePwd){
		SessionUser su = SessionKit.getSessionUser(request);
		SysUser user = sysUserService.selectById(su.getUserId());
		
		if(ObjKit.isNotEmpty(pwd)){
			if(!pwd.equals(rePwd)){
				return operateError("两次输入的密码不一致！");
			}
		}else{
			return operateError("新密码不能为空！");
		}
		if(ObjKit.isNotEmpty(oldPwd)){
			if(user.getLoginPwd().equals(passwordHash.toHex(oldPwd, user.getSalt()))){
				return operateError("原密码不正确！");
			}
		}else{
			return operateError("原密码不正确！");
		}
		
		try {
			SysUser newUser = new SysUser();
			newUser.setId(user.getId());
			newUser.setLoginPwd(passwordHash.toHex(pwd, user.getSalt()));
			
			sysUserService.updateById(newUser);
		} catch (Exception e) {
			log.error("修改密码出现未知错误！", e);
			return operateError("未知错误，请联系管理员！");
		}
		
		return operateSuccess("密码修改成功！");
	}
}
